package com.example.nna.voz;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Iterator;

import org.jsoup.Connection.Method;
import org.jsoup.Connection.Response;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.nodes.Node;
import org.jsoup.nodes.TextNode;
import org.jsoup.select.Elements;

import android.graphics.Bitmap;
import android.graphics.Typeface;
import android.util.Log;

import com.example.nna.util.UserInfo;

public class Parser3 {
	private String m_url;
	private Document doc;
	private Document doc2;
	private Element mainElement;
	private Response res;
	private ArrayList<containPage3> ListContains;
	private UserInfo mUser;
	private String mIndexPage;
	public String Urlpage; //ngoc an
	public String Urlprev;
	public String Urlnext;
	public String Urlfirst;
	public String Urllast;
	private int curPage;
	private int lastPage;
	private String m_title;
	private String mTextQuote;
	private boolean isSubscribe;
	public Parser3(String url){
		m_url = url;
		ListContains = new ArrayList<containPage3>();
		mUser = new UserInfo();
	}
    int parser() {
		try {
			if(mUser.cookies() == null){
		        //doc = Jsoup.parse(Voz.mAssests.loadString());
				doc = Jsoup.connect(m_url).timeout(60000).get();
			}else{
				
				doc = Jsoup.connect(m_url)
						.timeout(60000)
						.cookies(mUser.cookies())
						.get();
			}
			if(doc.select("td[class*=tcat]").first().text().equals("vBulletin Message")){
				return 1;
			}else{
				mainElement = doc.select("div[align=center]").get(1);
				ListContains.clear();
				PaserExecute();
				return 0;
			}
			
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return -1;
		}
		
    }
    public int Login(UserInfo user){
    	mUser = user;
    	try {
			res = Jsoup.connect("http://vozforums.com/login.php?do=login")
					  .timeout(60000)
					  .data("do","login")
					  .data("vb_login_username",mUser.User())
					  .data("cookieuser", "1")
					  .data("vb_login_password",mUser.Pass())
					  .data("s", " ")
					  .data("securitytoken", mUser.Token())
					  .data("vb_login_md5password", mUser.md5Pass())
					  .data("vb_login_md5password_utf", mUser.md5Pass())
					  .method(Method.POST)
				      .execute();
			if(res.cookie("vfuserid") != null){
				mUser.cookies(res.cookies());
				mUser.setLogin(true); 
				return parser();
			}else return -2;	
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return -2;
		}
		
    }
    public int Logout(){
    	String urlLogout=null;
    	urlLogout = "http://vozforums.com/login.php?do=logout&"+
    			"logouthash=" + mUser.Token();
    	try {
			res = Jsoup.connect(urlLogout)
						.timeout(60000)
						.method(Method.POST)
						.execute();
			mUser.cookies(res.cookies());
			mUser.setLogin(false); 
			return parser();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return -2;
		}
		
    }
    public boolean Subscribe(){
    	return isSubscribe;
    }
    private boolean isSubscribe(){
    	
    	Element threadtoolElement = mainElement.select("a:contains(Unsubscribe)").first() ;
    	if(threadtoolElement!= null){
    		Log.d("nna","true");
    		return true;
    	}
    	Log.d("nna","false");
    	return false;
    }
    
    private void PaserExecute(){
    	containPage3 mContain;
    	Element eleLogin = mainElement.select("a[href=private.php]").first();
		parsePage();
		isSubscribe = isSubscribe();
		if(eleLogin != null){
			String temp = mainElement.select("td[class=alt2]").get(0).select("a[href*=mem]").attr("href");
			temp = temp.split("=")[1];
			mUser.setUserId(temp);
	    	Element eleSecurity = mainElement.select("input[name*=securitytoken]").first();
	    	String secToken;
	    	secToken = eleSecurity.attr("value");
	    	mUser.setToken(secToken);
		}
		Bitmap avatar = null;
		String m_user,m_time,m_AvatartUrl;
		Elements eleTag1s = mainElement.select("td[id*=td_post]");

		Iterator<Element> iteTag1 = eleTag1s.iterator();
		long t = System.currentTimeMillis();
		mContain = new containPage3();
		if((eleTag1s.get(0) !=  null) && 
		   (eleTag1s.get(0).select("strong").first()!= null)){
			m_title = eleTag1s.get(0).select("strong").text();
		}
		mContain.setTitle(m_title);
		ListContains.add(mContain);
		while(iteTag1.hasNext()){
			long t1 = System.currentTimeMillis();
			mContain = new containPage3();
			Element eleTag1 = iteTag1.next();
			Element eleContain =  eleTag1.parent();
			Element eleAvatar = eleContain.previousElementSibling();
			Element eleTime = eleAvatar.previousElementSibling();
			m_AvatartUrl = eleAvatar.select("img[src*=avatars]").attr("src");
			m_user = eleAvatar.select("a[class=bigusername]").text();
			m_time = eleTime.text();
			Element elePostMessage = eleTag1.select("div[id*=post_message").first();
			if(elePostMessage!= null){
				mContain.setId(elePostMessage.attr("id").split("_")[2]);
		    	PaserPage3(elePostMessage,mContain,true,false);
				mContain.Info(m_user, m_time, avatar,m_AvatartUrl);
				
		    	ListContains.add(mContain);
			}
			Log.d("time", "containdoc:"+String.valueOf(System.currentTimeMillis() - t1));
		}
		ListContains.add( new containPage3());
		Log.d("time", "contain:"+String.valueOf(System.currentTimeMillis() - t));
    }
    private void PaserPage3(Element elePostMessage,containPage3 m_Contain,boolean write,boolean pre){
    	Element ele=null;
		if(elePostMessage.select("blockquote").first() != null){
			ele = elePostMessage.select("blockquote").first();
		}else{
			ele = elePostMessage;
		}
		if(ele != null){
			for (Node child : ele.childNodes()) {
				if(child instanceof Element){
					if(((Element)child).tagName().equals("div")){
						Element eleTemp = ((Element)child).select("div").first();
						m_Contain.addText("\n");
						PaserPage3(eleTemp,m_Contain,false,pre);
						m_Contain.addText("\n");
					}else if(((Element)child).tagName().equals("pre")){
						Element eleTemp = ((Element)child).select("pre").first();
						int start,end;
						start = m_Contain.getText().length();
						PaserPage3(eleTemp,m_Contain,false,true);
						end = m_Contain.getText().length();
						m_Contain.quote.add("", start,end);
					}else if(((Element)child).tagName().equals("ol")){
						Element eleTemp = ((Element)child).select("ol").first();
						PaserPage3(eleTemp,m_Contain,false,true);
					}else if(((Element)child).tagName().equals("li")){
						Element eleTemp = ((Element)child).select("li").first();
						PaserPage3(eleTemp,m_Contain,false,true);
					}else{
						if((((Element)child).select("table").first()) != null){
							Elements temp = ((Element)child).select("table");
							Element temp2,temp3;
							temp2 = temp.select("td[style*=border:1px inset]").first();
							if(temp2 != null){
								temp3 = temp2.select("div[style*=font-style:italic]").first();
								if(temp3!= null){
									int start,end;
									start = m_Contain.getText().length();
									m_Contain.addText(temp3.previousElementSibling().text() + "\n");
									PaserPage3(temp3,m_Contain,false,pre);
									end = m_Contain.getText().length();
									m_Contain.quote.add("", start, end);
									
								}else{
									int start,end;
									start = m_Contain.getText().length();
									PaserPage3(temp2,m_Contain,false,pre);
									end = m_Contain.getText().length();
									m_Contain.quote.add("", start, end);
								}
							}
						}else if(((Element)child).tagName().equals("img")){
							String urlImage = (((Element)child).select("img[src]").attr("src"));
							if(urlImage.subSequence(0, 20).equals("http://vozforums.com"))
								urlImage = urlImage.substring(20);
							int start,end;
							start = m_Contain.getText().length();
							end = start + 2;
							m_Contain.image.add(urlImage, start, end, taskLoadImage.DownloadImage("load"));
							//m_Contain.image.add(urlImage, start, end, null);
							m_Contain.addText("aa");
							
						}else if(((Element)child).tagName().equals("br")){
							m_Contain.addText("\n");
						}else if(((Element)child).tagName().equals("b")){
							Element eleTemp = ((Element)child).select("b").first();
							int start,end;
							start = m_Contain.getText().length();
							PaserPage3(eleTemp,m_Contain,false,pre);
							end = m_Contain.getText().length();
							m_Contain.type.add("", start, end,Typeface.BOLD_ITALIC);
						}else if(((Element)child).tagName().equals("u")){
							Element eleTemp = ((Element)child).select("u").first();
							int start,end;
							start = m_Contain.getText().length();
							PaserPage3(eleTemp,m_Contain,false,pre);
							end = m_Contain.getText().length();
							m_Contain.typeU.add("", start, end);
						}else if(((Element)child).tagName().equals("font")){
							Element eleTemp = ((Element)child).select("font").first();
							int start,end;
							String mfont="while",msize="3";
							if(((Element)child).select("font[color]").first()!=null) 
								mfont = ((Element)child).select("font[color]").attr("color");
							if(((Element)child).select("font[size]").first()!=null) 
								msize = ((Element)child).select("font[size]").attr("size");
							start = m_Contain.getText().length();
							PaserPage3(eleTemp, m_Contain,false,pre);
							end = m_Contain.getText().length();
							m_Contain.font.add("", start, end, mfont, Integer.parseInt(msize));
						}else if (((Element)child).tagName().equals("a")){
							String temp = ((Element)child).select("a[href]").attr("href");
							if(temp.contains("mailto:")){
								temp = temp.substring(7, temp.length());
							}else{
								temp = temp.substring(temp.indexOf("http"), temp.length());
							}
							temp=temp.replace("%3A",":");
							temp=temp.replace("%2F","/");
							temp=temp.replace("%3F","?");
							temp=temp.replace("%3D", "=");
							temp=temp.replace("%26", "&");
							int start,end;
							String tempText = ((Element)child).select("a[href]").text();
							start = m_Contain.getText().length();
							end = start + tempText.length();
							m_Contain.web.add(temp, start, end);
							m_Contain.addText(tempText);
						}else{
							m_Contain.addText(((Element)child).text());
							if(pre) m_Contain.addText("\n");
						}
					}
				}
			    if (child instanceof TextNode) {
			    	
			    	if(pre) m_Contain.addText(((TextNode) child).getWholeText());
			    	else m_Contain.addText(((TextNode) child).text());
			    }
			}
		}else{
			m_Contain.addText(elePostMessage.text());
		}
		
    }
    private void parsePage(){
    	Element elePage = mainElement.select("div[class=pagenav").first();
    	if(elePage!=null){
    		mIndexPage = elePage.select("td[class=vbmenu_control]").text();
    		m_url = Voz.URL+elePage.select("td[class=alt1] > a").first().attr("href");

    		curPage = Integer.parseInt(mIndexPage.split(" ")[1]);
    		lastPage = Integer.parseInt(mIndexPage.split(" ")[3]);
    		if(m_url.contains("&page=") != true){
    			m_url = m_url.concat("&page=1");
    		}
    		Urlnext = m_url.substring(0,m_url.length()-1).concat(String.valueOf(curPage+1));
    		
    		Urlprev = m_url.substring(0,m_url.length()-1).concat(String.valueOf(curPage-1));
    		if(Urlprev.contains("&page=0")){
    			Urlprev = Urlprev.split("&page")[0];
    		}
    		Urlfirst = m_url.split("&page")[0];
    		Urllast = Urlfirst.concat("&page=" + String.valueOf(lastPage));
    	}
    }
    public int UnSubscribe(String id){
    	try {
			res = Jsoup.connect("http://vozforums.com/subscription.php?do=removesubscription&t="+id)
					  .timeout(60000)
					  .cookies(mUser.cookies())
					  .method(Method.GET)
				      .execute();
		
			return parser();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return -2;
		}
    }
    public int Subscribe(String id){
    	try {
        	Element eleSecurity = mainElement.select("input[name*=securitytoken]").first();
        	String secToken = null;
        	if(eleSecurity != null )secToken = eleSecurity.attr("value");
			res = Jsoup.connect("http://vozforums.com/subscription.php?do=doaddsubscription&threadid="+id)
					  .timeout(60000)
					  .cookies(mUser.cookies())
					  .data("do","doaddsubscription")
	    			  .data("threadid",id)
	    			  .data("s"," ")
	    			  .data("url","index.php")
	    			  .data("emailupdate","0")
	    			  .data("folderid","0")
	    			  .data("securitytoken",secToken)
					  .method(Method.POST)
				      .execute();
			return parser();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return -2;
		}

    }
    public int QuoteGet(int iQuote,int type){
    	try {
    		String temp;
    		if(type == 0)//new reply
    			temp = "http://vozforums.com/newreply.php?do=newreply&p=";
    		else//edit post
    			temp = "http://vozforums.com/editpost.php?do=editpost&p=";
			res = Jsoup.connect(temp + getContains(iQuote).Id())
					  .timeout(60000)  
					  .cookies(mUser.cookies())
					  .method(Method.GET)
				      .execute();
			doc2 = res.parse();
			Element eleQuote = doc2.select("textarea[name=message]").first();
			if(eleQuote != null){
				mTextQuote = eleQuote.textNodes().get(0).getWholeText() ;
				return 0;
			}
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return -1;
		}
    	return -1;
    }
    public String getTextQuote(){
    	return mTextQuote;
    }
    public int PostEdit(String message){
    	Element eleUrl = mainElement.select("form[action*=editpost.php?do=updatepost]").first();
    	Element eleSecurity = mainElement.select("input[name*=securitytoken]").first();
    	Element elePostHash = mainElement.select("input[name*=posthash]").first();
    	Element elePostStartTime =mainElement.select("input[name*=poststarttime]").first();
    	Element eleP =mainElement.select("input[name=p]").first();
    	Element eleTitle =mainElement.select("input[name=title]").first();
    	String url,secToken = null,postHash=null,postStartTime=null,p=null,title=null;
    	if(eleSecurity != null )secToken = eleSecurity.attr("value");
    	if(elePostHash != null) postHash = elePostHash.attr("value");
    	if(elePostStartTime != null) postStartTime = elePostStartTime.attr("value");
    	if(eleP != null) p = eleP.attr("value");
    	if(eleTitle != null) title = eleTitle.attr("value");
    	try {
	    	if(eleUrl != null){
	    		url = eleUrl.attr("action");
	    		url = url.replace("&amp;","&");
	    		res = Jsoup.connect("http://vozforums.com/" + url)
	    				  .timeout(60000)
	    				  .cookies(mUser.cookies())
	    				  .data("title",title)
	    				  .data("message",message)
						  .data("wysiwyg","0")
						  .data("s", " ")
						  .data("securitytoken",secToken)
						  .data("do", "updatepost")
						  .data("p", p)
						  .data("posthash", postHash)
						  .data("poststarttime", postStartTime)
						  .data("sbutton", "Save Changes")
						  .data("parseurl", "1")
						  .data("emailupdate", "9999")
						  .method(Method.POST)
					      .execute();
	    		doc = res.parse();
	    		ListContains.clear();
	    		PaserExecute();
	    		return 0;
	    	}

		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return -1;
		}
    	return -1;
    }
    public int PostQuoteReply(String message){
    	Element eleUrl = mainElement.select("form[action*=newreply.php?do=postreply]").first();
    	Element eleSecurity = mainElement.select("input[name*=securitytoken]").first();
    	Element elePostHash = mainElement.select("input[name*=posthash]").first();
    	Element elePostStartTime =mainElement.select("input[name*=poststarttime]").first();
    	Element eleP =mainElement.select("input[name=p]").first();
    	Element eleTitle =mainElement.select("input[name=title]").first();
    	String url,secToken = null,postHash=null,postStartTime=null,p=null,title=null;
    	if(eleSecurity != null )secToken = eleSecurity.attr("value");
    	if(elePostHash != null) postHash = elePostHash.attr("value");
    	if(elePostStartTime != null) postStartTime = elePostStartTime.attr("value");
    	if(eleP != null) p = eleP.attr("value");
    	if(eleTitle != null) title = eleTitle.attr("value");
    	try {
	    	if(eleUrl != null){
	    		url = eleUrl.attr("action");
	    		url = url.replace("&amp;","&");
	    		res = Jsoup.connect("http://vozforums.com/" + url)
	    				  .timeout(60000)
	    				  .cookies(mUser.cookies())
	    				  .data("title",title)
	    				  .data("message",message)
						  .data("wysiwyg","0")
						  .data("securitytoken",secToken)
						  .data("do", "postreply")
						  .data("t", url.split("=")[2])
						  .data("p", p)
						  .data("specifiedpost", "1")
						  .data("s", " ")
						  .data("posthash", postHash)
						  .data("poststarttime", postStartTime)
						  .data("loggedinuser",mUser.UserId())
						  .data("multiquoteempty", "")
						  .data("sbutton", "Post Quick Reply")
						  .data("parseurl", "1")
						  .data("emailupdate", "9999")
						  .data("rating", "0")
						  .method(Method.POST)
					      .execute();
	    		doc = res.parse();
	    		ListContains.clear();
	    		PaserExecute();
	    		return 0;
	    	}

		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return -1;
		}
    	return -1;
    }
    public int PostQuickReply(String message){
    	Element eleUrl = mainElement.select("form[action*=newreply.php?do=postreply]").first();
    	Element eleSecurity = mainElement.select("input[name*=securitytoken]").first();
    	String url,secToken;
    	secToken = eleSecurity.attr("value");
    	try {
	    	if(eleUrl != null){
	    		url = eleUrl.attr("action");
	    		url = url.replace("&amp;","&");
	    		res = Jsoup.connect("http://vozforums.com/" + url)
	    				  .timeout(60000)
	    				  .cookies(mUser.cookies())
	    				  .data("message",message)
						  .data("wysiwyg","0")
						  .data("styleid", "0")
						  .data("fromquickreply", "1")
						  .data("s", " ")
						  .data("securitytoken",secToken)
						  .data("do", "postreply")
						  .data("t", url.split("=")[2])
						  .data("p", "who cares")
						  .data("specifiedpost", "0")
						  .data("parseurl", "1")
						  .data("loggedinuser",mUser.UserId())
						  .data("sbutton", "Post Quick Reply")
						  .method(Method.POST)
					      .execute();
	    		doc = res.parse();
	    		mainElement = doc.select("div[align=center]").get(1);
	    		ListContains.clear();
	    		PaserExecute();
	    		return 0;
	    	}

		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return -1;
		}
    	return -1;
    }
   
    public String getIndexPage(){
    	return mIndexPage;
    }
  
    public ArrayList<containPage3> getContains(){
    	return ListContains;
    }
    public containPage3 getContains(int index){
    	return ListContains.get(index);
    }
    public UserInfo mUserInfo(){
    	return mUser;
    }
    public String title(){
    	return m_title;
    }
    public void resetMultiQuote(){
    	for(int i=0;i<ListContains.size();i++)
    		ListContains.get(i).setMultiQuote(false);
    	mUser.cookies().remove("vbulletin_multiquote");
    }
}
